#include <iostream>
#include <sys/socket.h>
#include "../../socks/sock.h"
#include "../../socks/sockdist.h"

using namespace std;

int main(int argc, char** argv)
{
	if(argc > 1)
	{
		Sock BRclient(SOCK_STREAM, 0);
		int descBRclient;
		
		if(BRclient.good())
		{
			descBRclient = BRclient.getsDesc();
		}
		
		SockDist BRpublic(argv[1], (short)54001);
		struct sockaddr_in * addrBRpublic = BRpublic.getAdrDist();
		int lgAddrBRpublic = sizeof(struct sockaddr_in);
		
		sockaddr_in sAddr;
		socklen_t lgAddr = sizeof(sAddr);
		
		int r = getsockname(descBRclient, (struct sockaddr*) &sAddr, &lgAddr);
		
		if (!r)
		{
			cout << "Num Port : " << ntohs(sAddr.sin_port) << endl;
		}
		
		int res = connect(descBRclient, (struct sockaddr*)addrBRpublic, lgAddrBRpublic);
		
		if(res != -1)
		{
			cout << "Connection : OK" << endl;
			
			r = getsockname(descBRclient, (struct sockaddr*) &sAddr, &lgAddr);
		
			if (!r)
			{
				cout << "Num Port : " << ntohs(sAddr.sin_port) << endl;
			}
			
			uid_t uID = getuid();
			
			int resSend = send(descBRclient, &uID, sizeof(uID), 0);
			
			if(resSend != -1)
			{
				char buff[256];
				int resRecv = recv(descBRclient, buff, sizeof(buff), 0);
				
				if(resRecv != -1)
				{
					cout << buff << endl;
				}
				else
				{
					cout << "R" << endl;
				}
			}
			else
			{
				cout << "S" << endl;
			}
		
		}
		else
		{
			cout << "Connection : Error" << endl;
		}
	}
}
 
 
